const mongoose = require("mongoose");
const Blog = mongoose.model("blog");
const BlogVld = require("./blog.vld");
const { Resp } = require("../../config/utils");

class BlogCtrl {
  /**
   * @api {get} /acticles 获取文章列表
   * @apiName acticles_list
   * @apiGroup acticles
   * 
   * @apiHeader {String} vf token 
   * 
   * @apiParam {String} type 类型(可选)
   * @apiParam {String} pageNumber 页数
   * @apiParam {String} pageCount 每页个数
   * @apiSuccessExample 返回示例
      HTTP/1.1 200 OK
      {
        "code": 1,
        "msg": "获取文章成功！",
        "data": {
          "list": [],
          "count": 1
        }
      }
   * @apiErrorExample 错误示例
      HTTP/1.1 500 Internal Server Error
  */
  async getBlogs(ctx, next) {
    let { type, pageCount = 10, pageNumber = 1 } = ctx.query
    let cond = {}
    if(type) cond['tags'] = type
    let blogs = Blog.find(cond, 'title created_at')
      .populate("author")
      .sort({ created_at: -1 })
      .skip((Number(pageNumber) - 1) * Number(pageCount))
      .limit(Number(pageCount));
    let [list, count] = await Promise.all([ blogs, Blog.countDocuments().where(cond)])
    // list = list.map(item => {
    //   const im = item.toObject();
    //   delete im.author.password
    //   return im
    // })
    ctx.body = Resp(1, "获取文章成功！", {
      list, count
    })
  }
  /**
   * @api {get} /acticles/:id 获取文章详情
   * @apiName acticles_id
   * @apiGroup acticles
   * 
   * @apiHeader {String} vf token 
   * 
   * @apiParam {String} id 文章ID
   * @apiSuccessExample 返回示例
      HTTP/1.1 200 OK
      {
        "code": 1,
        "msg": "获取文章成功！!",
        "data": {}
      }
   * @apiErrorExample 错误示例
      HTTP/1.1 500 Internal Server Error
  */
  async getBlog(ctx, next) {
    let { id } = ctx.params;
    if (!id) {
      return (ctx.body = Resp(0, "缺少参数", null));
    }
    let result;
    try {
      result = await Blog.findOne({ _id: ctx.params.id }, { __v: 0 }).populate(
        "author"
      );
      result.lookCount++;
      result.save();
      const info = result.toObject();
      delete info.password;
      ctx.body = Resp(1, "获取文章成功！", info);
    } catch (error) {
      ctx.body = Resp(0, "未找到查询文章！", null);
    }
  }
  /**
   * @api {post} /acticles 新增文章
   * @apiName acticles_add
   * @apiGroup acticles
   * 
   * @apiHeader {String} vf token 
   * 
   * @apiParam {String} title 标题
   * @apiParam {String} content 内容
   * @apiParam {String} author 作者ID
   * @apiParam {String} tags 标签数组
   * @apiSuccessExample 返回示例
      HTTP/1.1 200 OK
      {
        "code": 1,
        "msg": "新增文章成功！",
        "data": {}
      }
   * @apiErrorExample 错误示例
      HTTP/1.1 500 Internal Server Error
  */
  async createBlogs(ctx, next) {
    let { title, content, author, tags } = ctx.request.body;
    let validate = await BlogVld.createBlog(title, content, author, tags);
    if (validate && validate.status === 0) {
      return (ctx.body = Resp(0, validate.msg, null));
    }
    let result = await Blog.create({ title, content, author, tags });
    return (ctx.body = Resp(1, "新增文章成功！", result));
  }
  /**
   * @api {put} /acticles 修改文章
   * @apiName acticles_put
   * @apiGroup acticles
   * 
   * @apiHeader {String} vf token 
   * 
   * @apiParam {String} _id 文章ID
   * @apiParam {String} title 标题
   * @apiParam {String} content 内容
   * @apiParam {String} author 作者ID
   * @apiParam {String} tags 标签数组
   * @apiSuccessExample 返回示例
      HTTP/1.1 200 OK
      {
        "code": 1,
        "msg": "修改文章成功！",
        "data": {}
      }
   * @apiErrorExample 错误示例
      HTTP/1.1 500 Internal Server Error
  */
  async updateBlogs(ctx, next) {
    let { _id, title, content, author, tags } = ctx.request.body;
    let validate = await BlogVld.updateBlog(_id, title, content, author, tags);
    if (validate && validate.status === 0) {
      return (ctx.body = Resp(0, validate.msg, null));
    }
    let result = await Blog.updateOne(
      { _id },
      { title, content, author, tags }
    );
    if (result.ok === 1) {
      return (ctx.body = Resp(1, "修改文章成功！", null));
    } else {
      return (ctx.body = Resp(1, "修改文章失败！", null));
    }
  }
  /**
   * @api {delete} /acticles/:id 删除文章
   * @apiName acticles_delete
   * @apiGroup acticles
   * 
   * @apiHeader {String} vf token 
   * 
   * @apiParam {String} id 文章ID
   * @apiSuccessExample 返回示例
      HTTP/1.1 200 OK
      {
        "code": 1,
        "msg": "删除文章成功！",
        "data": {}
      }
   * @apiErrorExample 错误示例
      HTTP/1.1 500 Internal Server Error
  */
  async deleteBlog(ctx, next) {
    let { id } = ctx.params;
    if (!id) {
      return (ctx.body = Resp(0, "缺少参数", null));
    }
    let result = await Blog.remove({ _id: id });
    if (result.ok === 1) {
      return (ctx.body = Resp(1, "删除文章成功！", null));
    } else {
      return (ctx.body = Resp(1, "删除文章失败！", null));
    }
  }
}

module.exports = new BlogCtrl();
